import {
  Body,
  Controller,
  Get,
  HttpCode,
  HttpException,
  HttpStatus,
  Param,
  Post,
  Query,
  Req,
  Res,
  UseGuards,
} from '@nestjs/common';
import { ChatApiService } from './chat-api.service';
import { askQuestionDto, changeGroupNameDto, saveMessageDto } from './dto/chat-api.dto';
import { GptGroup } from './entities/gptgroup.entity';
import { GptMessage } from './entities/gptMessage.entity';
import { TokenAuth } from 'src/common/gaurd/tokenAuth.gaurd';
import { PageVto } from 'src/common/Vto/page.vto';
import { PageDto } from '../user/dto/page.dto';
import { ApiBasicAuth, ApiBearerAuth, ApiHeader, ApiOkResponse, ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
import { query } from 'express';
import { User } from 'src/decorator/user.decorator';
import { Configuration, OpenAIApi } from 'openai';
import { IsNotEmpty } from 'class-validator';
import { Auth } from 'src/Decorators/Auth';
@Controller('chat-api')
@ApiTags('Chat')
@UseGuards(TokenAuth)
export class ChatApiController {
  constructor(private readonly chatApiService: ChatApiService) {}
  @ApiBearerAuth('token')
  @Post('/addGroup')
  @HttpCode(200)
  async addGroup(@User() user_id:number) {
    let result = await this.chatApiService.addGroup(user_id);
    console.log(result)
    if (result.raw.affectedRows > 0) {
      return {
        code: 1,
        id:result.generatedMaps[0].id,
        message: '新会话添加成功',
      };
    } else {
      return {
        code: 0,
        message: '添加失败',
      };
    }
  }

  
  @Get('/groupList')
  @ApiBearerAuth('token')
  @UseGuards(TokenAuth)
  @ApiOperation({
    description:'获取当前用户下的聊天组'
  })
  async getGroupList(@User() user_id: any, @Query() page: PageDto,@Query("name") name :string) {
    //  console.log(user_id,"23123123")
    let result =  await this.chatApiService.getGroupList(user_id,page,name);
    let val :PageVto<GptGroup> = {
      code:1,
      list:result[0],
      total:result[1],
      ...page
    }
    //  console.log(result)
    return val
  }
  


  @Get('/ask')
  @ApiBearerAuth('token')
  @ApiOperation({
    description:'提交问题'
  })
  async askQuestion(@Query() query: askQuestionDto, @Req() req: any): Promise<any> {
    let val :any = await this.chatApiService.getAnswer(query);
    console.log(val.data)
    // if(!conversation_id){
    //     await this.chatApiService.groupAddConversation_id(group_id,(val as any).data.conversation_id)
    // }
    // console.log(val)
  //  let result =  await this.chatApiService.saveMessage(question,(val as any).data.answer,group_id);  
      return {
        code:1,
        data:{
          answer:(val as any).data.answer,
          conversation_id:val.data.conversation_id,
        }
      }
  }
   
  @Auth("删除聊天组")
  @Get('/deleteGroup')
async deleteGroup(@Query('group_id') groupId :number,@User() user_id :number ){
    if(!groupId){
      throw Error
    }
   let result =  await this.chatApiService.deleteMessageGroup(groupId,user_id)
   if(result){
       return {
         code:1, 
         message:'删除成功'
       }
   }
}

  @ApiOperation({
    description:'获取群组下的聊天记录'
  })
  @ApiBasicAuth('token')
  @Get('/getMessageList')
  async getMessageList(@Query() page :PageDto,@Query('group_id') group_id :number){
     if(!group_id){
      return {
        code:0,
        message:'group_id not be null'
      }
     }
     let result =  await this.chatApiService.getMessageByGroupId(group_id,page)
      let val :PageVto<GptMessage> = {
        code:1,
        list:result.list,
        total:result.count,
        ...page
      }
      
    return val
      
  }
 
 
  @ApiOperation({
    description:"修改群组标题",

  })
  @ApiBasicAuth('token')
  @UseGuards(TokenAuth) 
  @Post('/changeTitle')
 async changeGroupName(@Query() query :changeGroupNameDto){
   let result =  await  this.chatApiService.changeGroupName(query)
   console.log(result)
   return {
      message:'修改成功',
      code:1
   }
  }
  
  @Post("/saveMessage")
  @Auth("保存信息")
  async saveMessage(@Body() body :saveMessageDto){
      await this.chatApiService.saveMessage(body)
      return {
        code:1
      }
  }
  

  @Get("/collectGroup")
  @Auth("收藏聊天组")
  async collectGroup(@Query("collect") collect :1|2,@Query("group_id") group_id :number){
     await this.chatApiService.collectGroup(collect,group_id)
     return {
        code:1,
        message:collect == 1?"收藏成功":"已取消收藏"
     }
  }

}
